package com.drone.drone_server.controller;

import com.drone.drone_server.api.ApiResponse;
import com.drone.drone_server.dao.DroneFlightRecordDao;
import com.drone.drone_server.dao.FlightFireRelationDao;
import com.drone.drone_server.entity.DroneFlightRecord;
import com.drone.drone_server.entity.FlightFireRelation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/flightRecord")
public class FlightRecordController {

    @Autowired
    private DroneFlightRecordDao droneFlightRecordDao;

    @Autowired
    private FlightFireRelationDao flightFireRelationDao;

    @GetMapping("/list")
    public ApiResponse getFlightRecords() {
        List<DroneFlightRecord> records = droneFlightRecordDao.selectList(null);
        return ApiResponse.success(records);
    }

    @PutMapping("/add")
    public ApiResponse addFlightRecord(
            @RequestParam("droneId") Integer droneId,
            @RequestParam("routeId") Integer routeId,
            @RequestParam("startTime") Date startTime,
            @RequestParam("endTime") Date endTime,
            @RequestParam("flightStatus") String flightStatus) {

        try {
            DroneFlightRecord record = new DroneFlightRecord();
            record.setDroneId(droneId);
            record.setRouteId(routeId);
            record.setStartTime(startTime);
            record.setEndTime(endTime);
            record.setFlightStatus(flightStatus);

            int result = droneFlightRecordDao.insert(record);
            if (result > 0) {
                return ApiResponse.success(record.getRecordId());
            }
            return ApiResponse.fail("添加飞行记录失败");
        } catch (Exception e) {
            return ApiResponse.fail("服务器错误: " + e.getMessage());
        }
    }

    @PutMapping("/addRelation")
    public ApiResponse addRelation(@RequestParam("flight_id") Integer recordId,@RequestParam("fire_id") Integer fireId){
        try {
            FlightFireRelation flightFireRelation = new FlightFireRelation();
            flightFireRelation.setFireId(fireId);
            flightFireRelation.setFlightId(recordId);
            int result = flightFireRelationDao.insert(flightFireRelation);
            if (result > 0) {
                return ApiResponse.success("添加飞行记录与火情关联成功");
            }
            return ApiResponse.fail("添加飞行记录与火情关联失败");
        } catch (Exception e) {
            return ApiResponse.fail("服务器错误: " + e.getMessage());
        }
    }
}
